<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogFormVisible"
    width="500px"
    @close="close"
    :close-on-click-modal="closeModel"
  >
    <el-form :model="form" label-width="80px" :rules="rules" ref="ruleForm">
      <el-form-item label="用户名" prop="username"
        ><el-input v-model="form.username" autocomplete="off"></el-input
      ></el-form-item>
      <el-form-item
        label="管理员ID"
        prop="parentId"
        v-if="form.roles == 'editor' && checkPermission(['root'])"
      >
        <el-input
          v-model="form.parentId"
          autocomplete="off"
          placeholder="该用户所属的团队管理对应的ID"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password"
        ><el-input v-model="form.password" autocomplete="off"></el-input
      ></el-form-item>
      <el-form-item label="余额"
        ><el-input v-model="form.money" autocomplete="off"></el-input
      ></el-form-item>
      <el-form-item label="头像">
        <el-row :gutter="6">
          <el-col :span="16"
            ><el-input v-model="form.avatar" autocomplete="off"></el-input
          ></el-col>
          <el-col :span="6">
            <el-upload
              action="/upload/"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <el-button size="mini" type="primary">上传</el-button>
            </el-upload>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item
        label="联盟账号"
        prop="useUnion"
        v-if="
          unionList.length > 0 && form.roles != 'admin' && form.roles != 'root'
        "
      >
        <el-select
          v-model="form.useUnion"
          placeholder="请选择使用的联盟账号"
          @change="reChannelList"
        >
          <el-option
            :label="name"
            :value="name"
            v-for="(name, index) in unionList"
            :key="index"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="媒体"
        prop="useUnion"
        v-if="
          unionList.length > 0 && form.roles != 'admin' && form.roles != 'root'
        "
      >
        <el-select
          v-model="form.useChannel"
          placeholder="请选择使用的媒体"
          style="width: 280px;"
        >
          <el-option
            :label="item.name + '(媒体ID：' + item.id + ')'"
            :value="item.id"
            v-for="(item, index) in channelList"
            :key="index"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="PID"
        prop="pid"
        v-if="
          form.useChannel.length > 0 &&
          form.roles != 'admin' &&
          form.roles != 'root'
        "
      >
        <el-input v-model="form.pid" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="用户备注">
        <el-input
          type="textarea"
          :autosize="{ minRows: 5, maxRows: 5 }"
          placeholder="可以记录用户的备注，历史PID等资料信息"
          v-model="form.remark"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="权限" prop="roles" v-if="checkPermission(['root'])">
        <el-select v-model="form.roles" placeholder="请选择用户权限">
          <el-option label="普通用户" value="editor"></el-option>
          <el-option label="管理员" value="admin"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import checkPermission from "@/utils/permission";
import { listUnionChannel } from "@/api/index";
export default {
  name: "TableEdit",
  props: {
    unionList: Array,
  },
  data() {
    var validatePass = (rule, value, callback) => {
      if (!this.isEdit) {
        if (value === "") {
          callback(new Error("请输入密码"));
        } else if (value.length < 6 || value.length > 16) {
          callback(new Error("密码长度在 6 到 16 个字符"));
        }
      } else {
        if (value != undefined && value != "" && value.length) {
          if (value.length < 6 || value.length > 16) {
            callback(new Error("密码长度在 6 到 16 个字符，不修改留空即可"));
          }
        }
      }
      callback();
    };
    return {
      form: {
        username: "",
        password: "",
        money: "0.00",
        useUnion: "",
        roles: "",
        pid: "",
        avatar: "",
        useChannel: "",
        parentId: 0,
        remark: "",
      },
      title: "",
      dialogFormVisible: false,
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 16,
            message: "用户名长度在 3 到 16 个字符",
            trigger: "blur",
          },
        ],
        parentId: [
          { required: true, message: "管理员ID不能为空" },
          { type: "number", message: "管理员ID为数字" },
        ],
        useUnion: [
          {
            required: true,
            message: "请选择使用的联盟账号",
            trigger: "change",
          },
        ],
        roles: [
          { required: true, message: "请选择用户权限", trigger: "change" },
        ],
        useChannel: [
          { required: true, message: "请选择使用的媒体", trigger: "change" },
        ],
        pid: [
          { required: true, message: "请设置对应账号的PID", trigger: "blur" },
        ],
        password: [{ validator: validatePass, trigger: "blur" }],
      },
      isEdit: false,
      closeModel: false,
      channelList: [],
    };
  },
  created() {},
  methods: {
    reChannelList() {
      this.form.useChannel = "";
      listUnionChannel({ unionName: this.form.useUnion }).then((res) => {
        this.channelList = res.data.channel;
      });
    },
    showEdit(row) {
      if (!row) {
        this.title = "增加新用户";
        this.isEdit = false;
      } else {
        this.title = "编辑用户资料";
        delete row.parentName;
        this.form = row;
        this.form.parentId = Number(this.form.parentId);
        this.isEdit = true;
        if (this.form.useChannel == 0) {
          this.form.useChannel = "";
        }
        if (this.form.useUnion != "") {
          listUnionChannel({ unionName: this.form.useUnion }).then((res) => {
            this.channelList = res.data;
          });
        }
      }
      this.dialogFormVisible = true;
    },
    close() {
      this.form = this.$options.data().form;
      this.dialogFormVisible = false;
    },
    save() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          if (this.form.roles == "editor") {
            let pidArr = this.form.pid.split("_");
            console.log(pidArr.length);
            if (this.form.pid.indexOf("mm_") != 0 && pidArr.length != 4) {
              this.$message.error("请设置正确PID，格式：mm_213123_52325_88888");
              return false;
            }
            if (
              this.form.pid.indexOf(this.form.useChannel) === -1 ||
              this.form.useChannel != pidArr[2]
            ) {
              this.$message.error(
                "请务必设置对应媒体的Pid，当前媒体ID：" +
                  this.form.useChannel +
                  "，PID媒体ID为：" +
                  pidArr[2]
              );
              return false;
            }
          }
          console.log(this.form);
          let setdata = this.form;
          setdata.isEdit = this.isEdit;
          this.$emit("msgEvent", setdata);
          return false;
        } else {
          return false;
        }
      });
    },
    handleAvatarSuccess(res, file) {
      if (res.code === 10000) {
        this.form.avatar = "/" + res.data;
      } else {
        this.$message.error(res.msg);
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 3;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG/PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 3MB!");
      }
      return isJPG && isLt2M;
    },
    checkPermission,
  },
};
</script>
<style lang="scss" scoped></style>
